package com.cyf.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Map;

//描述切面类
@Aspect
@Configuration
@Component
public class HttpControllerAop {

    private static final Logger logger = LoggerFactory.getLogger(HttpControllerAop.class);

    /**
     *  定义切点Pointcut
     */
    //@Pointcut("execution(* com.cyf.wechat.service.WechatHttpController.*(..)) || execution(* com.cyf.third.kuting.service.KTHttpController.*(..)) || execution(* com.cyf.app.AppHttpController.*(..)) || execution(* com.cyf.app.AppPayHttpController.*(..)) || execution(* com.cyf.pay.alipay.AlipayHttpController.*(..)) || execution(* com.cyf.pay.wxpay.WxpayHttpController.*(..))")
    @Pointcut("execution(* com.cyf..*HttpController.*(..))")
    public void excudeService() {
    }

    @Around("excudeService()")
    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
        ObjectMapper mapper = new ObjectMapper();

        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) ra;
        HttpServletRequest request = sra.getRequest();

        String uri = request.getRequestURI();
        String queryString = request.getQueryString();
        Map<String, String[]> params = request.getParameterMap();
        if (params != null) {
            queryString = mapper.writeValueAsString(params);
        }
        String method = request.getMethod();
        if ("POST".equals(method)) {
            Object[] paramsArray = pjp.getArgs();
            if (paramsArray != null && paramsArray.length > 0) {
                queryString = mapper.writeValueAsString(paramsArray[0]);
            }
        }
        logger.info("请求uri: ({}), params: {}", uri, queryString);

        // result的值就是被拦截方法的返回值
        Object result = pjp.proceed();

        // 过滤 高频或数据量大的日志，不打印
        String[] skipRsp = new String[]{"/getFile", "/app/getInfo", "/shpay/getCarInInfo"};
        boolean printRspLog = !Arrays.asList(skipRsp).contains(uri);
        if (printRspLog) {
            logger.info("请求结束，controller的返回值是：{}", mapper.writeValueAsString(result));
        }
        return result;
    }

}